<?php

namespace App\Recharge\Service;

use App\Jobs\OrderCallbackNotify;
use Throwable;
use App\Recharge\Library;
use Psr\Log\LoggerInterface;
use App\Recharge\Logic\ConfigLogic;
use Illuminate\Support\Facades\Log;

class DirectChargingService extends BaseService
{
    /**
     * @return void
     */
    public function execute(): void
    {
        try {
            // 主商品
            $this->mainGood();
            // 配置
            $config = new ConfigLogic();
            // 接口配置
            $api = $this->cg->getApiConfig($this->bean->getGood()->Supplier_status);
            // 供应商第三方配置
            $supConfig = $config->supplierApiConfigCheck($api);
            // 第三方价格检测
            $this->goodLogic->thirdGoodUnitPriceCheck($api, $supConfig, $this->bean->getGood());
            // 生成bean
            $bean = $config->makeBasicInformation($api, $this->order, $this->bean->getGood(), $supConfig);
            // 下单
            $result = Library::executeRecharge($this->obtainApiInterface($api), httpClient(), $api, $bean);
            $update = [];
            if ($result->getErrorMessage() != '') {
                $update = ['msg' => $result->getErrorMessage()];
            }
            // 检测是否发送了resp 而且有trade_no
            if ($result->isSendApi() && $api->trade_no_key != '') {
                $update['merchantOrderNum'] = data_get($result->getFormatResponse(), $api->trade_no_key, '');
            }
            if ($result->isResult()) {
                if (!empty($update)){
                    $this->order->update($update);
                }
            } else {
                if ($this->bean->getGood()->order_status == 2){
                    OrderCallbackNotify::dispatch($this->order, false)->onQueue('h5_notify');
                }
            }
            if ($result->getApiSynchronousEndProcessing()) {
                $result->getApiSynchronousEndProcessing()();
            }
        } catch (Throwable $e) {
            $this->log()->error('充值下单失败', [
                'supplier'  => $this->supplier->toArray(),
                'bean'      => $this->bean->toArray(),
                'error'     => error2array($e),
            ]);
        }
    }

    /**
     * @return LoggerInterface
     */
    protected function log(): LoggerInterface
    {
        return Log::channel('api-direct');
    }

}
